Hệ thống quản lý trường học bằng PHP / MySQLi
1 <?php
2 error_reporting(0);
3
4 backupDatabaseTables('localhost','root','','sms2');
5 /**
6 * @function backupDatabaseTables
7 * @author CodexWorld
8 * @link http://www.codexworld.com
9 * @usage Backup database tables and save in SQL file
10 */
11 function backupDatabaseTables($dbHost,$dbUsername,$dbPassword,$dbName,$tables = '*'){
12 //connect & select the database
13 $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
14
15
16 //get all of the tables
17 if($tables == '*'){
18 $tables = array();
19 $result = $db->query("SHOW TABLES");
20 while($row = $result->fetch_row()){
21 $tables[] = $row[0];
22 }
23 }else{
24 $tables = is_array($tables)?$tables:explode(',',$tables);
25 }
26 $return='';
27 //loop through the tables
28
29 foreach($tables as $table){
30 $result = $db->query("SELECT * FROM $table");
31 $numColumns = $result->field_count;
32
33 //$return .= "DROP TABLE $table;";//ignored this line as i dont need to drop any table
34
35 $result2 = $db->query("SHOW CREATE TABLE $table");
36 $row2 = $result2->fetch_row();
37
38 $return .= "\n\n".$row2[1].";\n\n";
39
40 for($i = 0; $i < $numColumns; $i++){
41 while($row = $result->fetch_row()){
42
43 $return .= "INSERT INTO $table VALUES(";
44 for($j=0; $j < $numColumns; $j++){
45 $row[$j] = addslashes($row[$j]);
46 $row[$j] = ereg_replace("\n","\\n",$row[$j]);
47 if (isset($row[$j])) { $return .= '"'.$row[$j].'"' ; } else { $return .= '""'; }
48 if ($j < ($numColumns-1)) { $return.= ','; }
49 }
50 $return .= ");\n";
51 }
52 }
53
54 $return .= "\n\n\n";
55 }
56
57
58 //save file in the backup folder created on the desktop. the path may be adjusted later.
59 if(!is_dir('backup')){
60 mkdir('backup');
61 }
62 if(!is_file('sms2-backup-'.DATE('Y-m-d').'.sql')){
63 file_put_contents('sms2-backup-'.DATE('Y-m-d').'.sql', '');
64 }
65 $handle = fopen('backup/sms2-backup-'.DATE('Y-m-d').'.sql','w+');
66 fwrite($handle,$return);
67 fclose($handle);
68 }
69 ?>
70 <script>
71 alert('Data backup process Succsessful.');
72 window.location = "homepage.php";
73 </script>